// 1. 引入 ioredis
import Redis from 'ioredis';

// 2. 读取配置
import config from './config.js'

const opt = {
  db: config.REDIS_DB,
  host: config.REDIS_HOST,
  port: config.REDIS_PORT,
  prefix: "koa2:" //前缀
}

class RedisStore {
  constructor() {
    /**
          redisConfig: {
              prefix: 'DATASESS', //redis前缀
              dataPrefix: 'DATAPREFIX',   //redis数据存储前缀
              port: 6379, //端口
              host: '0.0.0.0',    //你的redisIP
              password: 'xxxxxx', //你的redis密码 无密码可以为空
              db: 0,  //默认存储库
              ttl: 60 * 60 * 24, //过期时间
              options: {} //其它配置
          },
       */
    this.redis = new Redis(opt);
  }
  /**
   * 设置redis data
   * @param {*} key
   * @param {*} data
   * @param {*} maxAge
   * @param {*} ex
   */
  async setData (key, data, maxAge = 60 * 60 * 24, ex = 'EX') {
    let status = null;
    try {
      if (data && typeof data == 'object') {
        status = await this.redis.set(`${opt.prefix}:${key}`, JSON.stringify(data), ex, maxAge);
      } else {
        status = await this.redis.set(`${opt.prefix}:${key}`, data, ex, maxAge);
      }
    } catch (error) {
      console.error(`设置data出错:`, error);
    }
    return status === 'OK';
  }

  /**
   * 获取redis的data
   * @param {*} key
   */
  async getData (key) {
    try {
      //const KEY = md5(key); //转成大写的MD5作为key
      const data = await this.redis.get(`${opt.prefix}:${key}`);
      return data;
    } catch (error) {
      console.error(`设置data出错:`, error);
    }
  }

  /**
   * 删除redis的data
   * @param {*} key
   */
  async delData (key) {
    let status = null;
    try {
      const KEY = getUCMd5(key); //转成大写的MD5作为key
      status = await this.redis.del(`${config.redisConfig.dataPrefix}:${KEY}`);
    } catch (error) {
      console.error(`删除data出错:`, error);
    }
    return status > 0;
  }
}

let instance = new RedisStore();

export default instance;